package com.shangcg.util;

import com.shangcg.service.SellTicket;
import com.shangcg.service.impl.SellTicketImpl;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 使用不加锁的方式，利用原子操作卖票，保证线程安全
 */
public class SellTicketUtilWithAtomic {

    public void sellTicket(){
        SellTicket sellTicket = new SellTicketImpl();
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 10, 100, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(20));

        threadPoolExecutor.execute(() ->{
            for (int i = 0; i < 60; i++){
                sellTicket.sellTicketWithAtomic();
            }
        });

        threadPoolExecutor.execute(() ->{
            for (int i = 0; i< 60; i++){
                sellTicket.sellTicketWithAtomic();
            }
        });
    }

    public static void main(String[] args) {
        SellTicketUtilWithAtomic sellTicketUtilWithAtomic = new SellTicketUtilWithAtomic();
        sellTicketUtilWithAtomic.sellTicket();
    }


}
